<template>
  <div class="main-container">
    <!-- 平台、用户选择部分 -->
    <div class="data-show">
      <div class="data-title">
        <h3>筛选</h3>
      </div>
      <div class="data-table data-table-filter">
        <!-- 平台 -->
        <div class="condition-item">
          <label class="condition-label">平台选择</label>
          <el-select 
            class="condition-input" 
            :disabled="systems.length < 1"
            v-model="pageData.systemId" 
            clearable 
            placeholder="请选择平台"
            @change="systemChange"
          >
            <el-option v-for="(item, index) in systems" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </div>
        <!-- 用户 -->
        <div class="condition-item">
          <label class="condition-label">用户选择</label>
          <el-select 
            class="condition-input" 
            :disabled="users.length < 1"
            v-model="pageData.userId" 
            clearable 
            placeholder="请选择用户"
            @change="userChange"
          >
            <el-option v-for="(item, index) in users" :key="index" :label="item.username" :value="item.id"></el-option>
            <el-select-loading
              :hasMore="userObj.hasMore"
              :page="userObj.page"
              :loading="userObj.loading"
              @load-more="userObj.loadingMore"
            />
          </el-select>
        </div>
      </div>
    </div>
    <!-- 用户信息 -->
    <div class="data-show">
      <div class="data-title data-title-between">
        <h3>目标信息</h3>
        <div class="data-title-actions">
          <span class="action aniTxtBtn" @click="getUserTag">生成标签</span>
          <span class="action aniTxtBtn" @click="linkToGroup">生成群组</span>
          <span class="action aniTxtBtn" @click="linkToGenerate">载体生成</span>
        </div>
      </div>
      <div class="data-table">
        <el-row class="fixed-row">
          <!-- 定位头像 -->
          <div class="avatar">
            <el-image :src="getImg(userInfo.user_avatar)" fit="contain" />
          </div>
          <!-- 第一个信息部分 -->
          <el-col class="col" :span="7">
            <div class="col-item">
              <label class="col-item-label">昵称：</label>
              <p class="col-item-content">{{ userInfo.user_name ? userInfo.user_name : '暂未提供' }}</p>
            </div>
            <div class="col-item">
              <label class="col-item-label">性别：</label>
              <p class="col-item-content">{{ userInfo.gender ? userInfo.gender : '男' }}</p>
            </div>
          </el-col>
          <!-- 第二个信息部分 -->
          <el-col class="col" :span="7">
            <div class="col-item">
              <label class="col-item-label">平台：</label>
              <p class="col-item-content">{{ getShow(userInfo.system, 'value', systems, 'name') }}</p>
            </div>
            <div class="col-item">
              <label class="col-item-label">所在地：</label>
              <p class="col-item-content">{{ userInfo.area ? userInfo.area : '暂无' }}</p>
            </div>
          </el-col>
          <!-- 第三个信息部分 -->
          <el-col class="col col-padding" :span="10">
            <div class="col-item col-item-fill">
              <label class="col-item-label">简介：</label>
              <p>{{ userInfo.introduction ? userInfo.introduction : '暂无简介' }}</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 底下的两列布局 -->
    <el-row class="m_t-2" :gutter="20">
      <el-col :span="18">
        <Condition v-if="recommends.length > 0">
          <Recommend 
            v-for="(item, index) in recommends" 
            :content="item.content"
            :user="item.user"
            :images="item.resource"
            :system="item.system"
            :supportNums="item.like_num"
            :commentNums="item.comment_num"
            :forwardNums="item.re_num"
            :time="item.collect_time"
            :key="index"
          ></Recommend>
        </Condition>
        <Condition v-else>
          <div class="recommend-empty">
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </div>
        </Condition>
      </el-col>
      <el-col class="flex-col" :span="6">
        <!-- 个性化推荐部分 -->
        <div class="data-show m_t-0">
          <div class="data-title">
            <h3>个性化推荐标签</h3>
          </div>
          <div class="data-table data-tag-content">
            <template v-if="tags.length > 0">
              <div class="common-row">
                <div class="common-item-tag item-10">
                  <h4>RMSE</h4>
                  <h4>{{ tagRMSE ? tagRMSE : '-' }}</h4>
                </div>
              </div>
              <el-tag class="data-tag" type="primary" v-for="(item, index) in tags" :key="index">{{ item }}</el-tag>
            </template>
            <div class="tag-empty" v-else>
              <h6 class="tag-data-empty">暂无个性化标签</h6>
              <h6 class="tag-data-empty">请选择平台及用户</h6>
              <h6 class="tag-data-empty">点击生成标签</h6>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, computed, onActivated } from 'vue';
import { API } from '@/utils/status';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import Condition from '@/components/common/Condition.vue';
import Recommend from '@/components/common/recommend.vue';
import avatar from '@/assets/images/four/avatar.jpeg';
import ElSelectLoading from '@/components/common/ElSelectLoading.vue';
import useAppStore from '@/stores/app';
import * as request from '@/api/recommend';

// 假数据目标信息
const defaultUserInfo = {
  user_name: '',
  gender: '',
  system: 2,
  area: '',
  introduction: '',
  user_avatar: ''
};

// ============> data <============
const appStore = useAppStore();
const router = useRouter();
const userObj = ref({
  page: 1,
  loading: false,
  hasMore: true,
  loadingMore(e){
    console.log(e);
    userObj.value.loading = true;
    request.getUserList({ platformId: pageData.value.systemId, page: e })
      .then(res => {
        let result = JSON.parse(res);
        console.log(result)
        userObj.value.loading = false;
        if (result && result.code === 200 && result.data.users && result.data.users.length > 0){
          const userData = result && result.code === 200 && result.data && result.data.users ? result.data.users : [];
          if (e === 1){
            users.value = [];
          }
          users.value.push(...userData);
          userObj.value.hasMore = users.value.length < result.data.total;
          userObj.value.page = e;
        }
      })
      .catch(err => {
        console.log(err);
        userObj.value.loading = false;
      })
  }
});
// 平台选择下拉数据
const systems = ref([]);
// 用户选择下拉数据
const users = ref([]);
// 根据用户选择获取到的用户信息
const userInfo = ref({
  user_name: '',
  gender: '',
  system: null,
  area: '',
  introduction: '',
  user_avatar: ''
});
// 用户选择获取的用户推文
const recommends = ref([]);
// 用户推文
const tags = ref([]);
// 用户推文系数
const tagRMSE = ref(null);
const pageData = ref({
  systemId: null,
  userId: null,
  // 推文数据
  data: []
});

const getShow = computed(() => {
  return function (v, k, arr, returnKey) {
    let obj = arr.find((item) => item[k] === v);
    let res = obj ? obj[returnKey] : "";
    return res;
  };
});
const getImg = computed(() => {
  return function (img){
    return img ? `${import.meta.env.VITE_APP_BASE_API}/${img}` : avatar;
  }
});

// ============> hooks <===========
// 初始化平台数据
getSystems();
onActivated(() => {
  if (systems.value.length < 1){
    getSystems();
  }
});

// ============> method <============
// 查询平台列表 - 更新systems
function getSystems(){
  request.getPlatform()
    .then(res => {
      let result;
      if (res) {
        result = JSON.parse(res);
        systems.value = result && result.code === 200 && result.data ? result.data : [];
      }
    })
}
// 根据平台拉取用户列表
function getUsers(){
  // todo - 这里要设计使用page分页拉取用户列表
  request.getUserList({ platformId: pageData.value.systemId, page: userObj.value.page })
    .then(res => {
      let result = JSON.parse(res);
      console.log(result);
      if (result && result.code === 200){
        users.value = result.data && result.data.users ? result.data.users : [];
        userObj.value.page = users.value.length > 0 ? 1 : 0;
      }
    })
}
// 平台选择事件
function systemChange(e){
  userObj.value.page = 1;
  userObj.value.loading = false;
  userObj.value.hasMore = true;
  if (typeof e === 'number'){
    pageData.value.systemId = e;
    pageData.value.userId = null;
    users.value = [];
    // todo - 这里的用户列表拉选要改为下拉滚动分页
    getUsers();
  } else {
    pageData.value.systemId = null;
    pageData.value.userId = null;
    //systemId: null,userId: null,
    users.value = [];

  }
}
// 用户选择事件
function userChange(e){
  if (e){
    getUserInfo();
    getUserPoster();
  } else {
    userInfo.value = Object.assign({}, defaultUserInfo);
    pageData.value.data = [];
  }
}
// 根据用户选择查询 - 用户详情
function getUserInfo(){
  request.getUserInfoById({
    userId: pageData.value.userId,
    platformId: pageData.value.systemId
  })
    .then(res => {
      let result;
      if (res){
        result = JSON.parse(res);
        userInfo.value = result && result.code === 200 && result.data ? result.data : defaultUserInfo;
        userInfo.value.system = pageData.value.systemId;
      }
    })
}
// 根据用户选择查询 - 用户推文
function getUserPoster(){
  //userId, platformId, page
  request.getPosterByUser({
    userId: pageData.value.userId,
    platformId: pageData.value.systemId,
    page: 1
  })
    .then(res => {
      let result;
      if (res){
        result = JSON.parse(res);
        recommends.value = result && result.data && result.data.posters ? result.data.posters : [];
        if (Array.isArray(recommends.value) && recommends.value.length > 0){
          recommends.value.forEach(recommend => {
            if (Array.isArray(recommend.resource) && recommend.resource.length > 0 ){
              recommend.resource.forEach(item => {
                item.srcList = [getImg.value(item.resource_url)];
              })
            }
          })
        }
        ElMessage.success('成功获取用户推文');
        /*
          {
            collect_time
            comment_num
            content
            id
            like_num
            platform: { id, name }
            publish_time
            re_num
            resource
            user: { id, username, nickname, avatar, fans_count, follows_count, friend_count}
            user_id
          }
        */
      }
    })
}
// 根据用户选择查询 - 用户推荐标签
function getUserTag(){
  if (typeof pageData.value.systemId != 'number' || (typeof pageData.value.userId != 'number' && typeof pageData.value.userId != 'string')){
    ElMessage.warning('请先选择平台及用户!');
    return;
  }
  appStore.openLoading('个性化标签生成中...');
  request.geTagByUser({
    userId: pageData.value.userId,
    platformId: pageData.value.systemId
  })
    .then(res => {
      appStore.closeLoading();
      let result = JSON.parse(res);
      if (result && result.code === 200 && result.data && result.data.tags && Array.isArray(result.data.tags)){
        tags.value = result.data.tags;
        tagRMSE.value = result.data.rmse;
        ElMessage.success('生成个性化标签成功');
      } else {
        let msg = result.msg || result.message || '生成个性化标签失败，请稍后重试或联系管理员';
        ElMessage.error(msg);
      }
    })
    .catch(err => {
      console.log(err);
      appStore.closeLoading();
    })
}
// 跳转到群组页面
function linkToGroup(){
  if (typeof pageData.value.systemId != 'number' || (typeof pageData.value.userId != 'number' && typeof pageData.value.userId != 'string')){
    ElMessage.warning('请先选择平台及用户!');
    return;
  }
  router.push({ 
    name: 'group', 
    query: { 
      userId: pageData.value.userId, 
      platformId: pageData.value.systemId
    } 
  });
}
// 跳转到生成页面
function linkToGenerate(){
  if (typeof pageData.value.systemId != 'number' || (typeof pageData.value.userId != 'number' && typeof pageData.value.userId != 'string')){
    ElMessage.warning('请先选择平台及用户!');
    return;
  }
  router.push({ 
    name: 'generate',
    query: {
      userId: pageData.value.userId, 
      platformId: pageData.value.systemId
    }
  });
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.condition-item {
  width: 48%;
  height: 50px;
  margin: 0;
}
.data-table-filter {
  @include flex-around-center;
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
.fixed-row {
  height: 100px;
  // background-color: red;
  width: calc(100% - 100px);
  margin-left: 100px;
  position: relative;
  // 头像部分
  .avatar {
    position: absolute;
    width: 100px;
    height: 100px;
    left: -100px;
    // background-color: yellow;
    padding: 10px;
    .el-image {
      @include wh-100;
      border-radius: 8px;
    }
  }
  .col {
    padding: 10px;
    .col-item {
      width: 100%;
      height: 30px;
      line-height: 30px;
      display: flex;
      margin: 5px 0;
      .col-item-label {
        color: var(--color-gray-10);
      }
      .col-item-content {
        @include text-overflow;
      }
    }
    .col-item-fill {
      display: block; 
      height: 100%;
      margin: 5px 0;
    }
  }
  .col-padding {
    padding-top: 5px;
  }
}
.data-tag-content {
  min-height: 250px;
}
.data-tag {
  margin: 10px 10px;
  cursor: pointer;
}
.flex-col {
  display: flex;
  flex-direction: column;
}
.article-item {
  width: 100%;
  margin-top: 10px;
}
.article-item-flex {
  @include flex-around-center;
  .yzx-label {
    margin-right: 5px;
    color: var(--color-gray-10);
  }
  .yzx-content {
    color: var(--color-black-10);
  }
}
.recommend-empty {
  width: 100%;
  height: 48vh!important;
  // background-color: var(--color-main-3);
  background-color: var(--color-gray-5);
  @include flex-all-center;
  // 无数据提示语
  .data-empty {
    // color: var(--color-white-10);
    color: var(--color-main-5);
    font-size: 28px;
  }
  // 无数据图标
  .data-empty-icon {
    // color: var(--color-white-10);
    color: var(--color-main-5);
    font-size: 80px;
  }
}
.tag-empty {
  width: 100%;
  min-height: 250px;
  background-color: var(--color-gray-5);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .tag-data-empty {
    // color: var(--color-white-10);
    color: var(--color-main-5);
    font-size: 16px;
    margin: 10px;
  }
}
.common-item-tag {
  width: 100%;
  height: 50px;
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  padding: 10px 15px;  
  background-color: var(--color-gray-2);
  overflow: hidden;
  @include flex-around-center;
}
</style>